/**
 * @name 根据字段获取规则索引
 * @param {Array} rules
 * @param {String} key
 * @returns
 */

export const getRuleIndex = (rules = [], key) => {
  return rules.findIndex(i => i.field === key);
};

/**
 * @name 根据字段获取规则
 * @param {Array} rules
 * @param {String} key
 * @returns
 */
export const getRule = (rules = [], key) => {
  return rules[getRuleIndex(rules, key)];
};

/**
 * @name 移除规则
 * @param {Array} rules
 * @param {String} key
 */

export const removeRule = (rules = [], key) => {
  const index = getRuleIndex(rules, key);
  if (index < 0) return;
  return rules.splice(index, 1);
};

/**
 * @name 指定字段前插入规则
 * @param {Array} rules
 * @param {String} key
 * @param {Array} newRules
 * @returns
 */
export const insertRuleBefore = (rules = [], key, newRules = []) => {
  const index = getRuleIndex(rules, key);
  if (index < 0) return;
  rules.splice(index, 0, ...newRules);
};

/**
 * @name 指定字段后插入规则
 * @param {*} formRule
 * @returns
 */
export const insertAfter = (rules = [], key, newRules = []) => {
  const index = getRuleIndex(rules, key);
  if (index < 0) return;
  rules.splice(index + 1, 0, ...newRules);
};

/**
 * @description 获取表单规则的数据结构
 * @param {Object} formRule 该目录下的表单规则
 */
export const getData = formRule => {
  const output = {};
  let list = [];
  if (formRule instanceof Function) list = formRule();
  if (formRule instanceof Array) list = formRule;
  list.forEach(rule => {
    if (!rule) return;
    const { type, value, field } = rule;
    if (value !== undefined) {
      output[field] = value;
    }
  });
  return output;
};
/**
 * @description 生成搜索栏的表单设置配置
 */
export const searchFormOptions = (labelWidth = "80px") => {
  return {
    form: {
      size: "mini",
      labelPosition: "right"
    },
    row: {
      gutter: 1,
      type: "flex",
      align: "center",
      justify: "start"
    },
    size: "mini",
    submitBtn: false,
    resetBtn: false,
    wrap: {
      labelWidth: labelWidth
    }
  };
};
/**
 * @description 生成表单填写栏的表单设置配置
 */
export const editFormOptions = (labelWidth = "110px") => {
  return {
    form: {
      size: "small",
      labelPosition: "center"
    },
    row: {
      gutter: 12,
      type: "flex",
      align: "center",
      justify: "start"
    },
    size: "small",
    submitBtn: false,
    resetBtn: false,
    wrap: {
      labelWidth: labelWidth
    }
  };
};

export * as autocomplete from "./common/autoComplete";
